package chordcows;
import java.net.*;
import java.io.*;

/**
 *
 * @author chris day
 * @project everyonesBOX
 */
public class SocketHandler implements Runnable {
	private Socket Client;
	private String Directory;

	public SocketHandler(Socket client, String directory) {
		this.Client = client;
		this.Directory = directory;
	}

	public void run() {
		BufferedReader receiver = null;
		OutputStream output=null;
		try {
			receiver = new BufferedReader(new InputStreamReader(Client.getInputStream()));
			output = Client.getOutputStream();
			PrintStream transmitter = new PrintStream(output);

			String filename = receiver.readLine();
			filename = Directory +"/"+ filename;
			File file = new File(filename);

			if(file.exists()) {
				transmitter.println("true");
				//transmitter.flush();
				String ack = receiver.readLine();
				if(!ack.equals("ack")) {
					System.out.println("Response was: " + ack);
					System.exit(1);
				}

				byte [] bytearray  = new byte [(int)file.length()];
				BufferedInputStream filestream = new BufferedInputStream(new FileInputStream(file));
				int cow = filestream.read(bytearray, 0, bytearray.length);
				System.out.println("size "+ file.length()+ "sent "+cow);
				System.out.println("Sending " + filename + "...");
				output.write(bytearray, 0, bytearray.length);
				output.flush();
			} else {
				transmitter.println("false");
			}
		} catch (IOException ex) {
			System.err.println("Unable to establish socket reader/writers: " + ex);
		} finally {
			try {
				output.close();
				Client.close();
			} catch (IOException ex) {
				System.err.println("Trouble closing Client: " + ex);
			}
		}
	}
}